package com.aiyige.utils.httpcache;

import android.content.pm.PackageInfo;
import android.os.Environment;
import android.util.Log;

import com.aiyige.MyApp;
import com.jakewharton.disklrucache.DiskLruCache;
import com.vondear.rxtools.RxTool;

import java.io.File;

import timber.log.Timber;

/**
 * Created by zhuyakun on 2018/1/12.
 */

public class HttpCache {
    public static final int ENTRY_KEY_VALUE = 0;
    public static final int ENTRY_KEY_CACHE_DURATION = 1;
    public static final int ENTRY_KEY_CACHE_TIMESTAMP = 2;
    DiskLruCache cache;

    private HttpCache() {
        try {
            cache = DiskLruCache.open(getDiskCacheDir(), getAppVersion(), 3, Integer.MAX_VALUE);
        } catch (Exception e) {
            Timber.e("HttpCache:" + Log.getStackTraceString(e));
            cache = null;
        }
    }

    private static HttpCache httpCache = null;

    public static HttpCache getInstance() {
        if (httpCache == null) {
            httpCache = new HttpCache();
        }
        return httpCache;
    }

    public void put(String url, String value, long cacheDuration) {
        try {
            String cacheKey = RxTool.Md5(url);
            DiskLruCache.Editor editor = cache.edit(cacheKey);
            editor.set(ENTRY_KEY_VALUE, value);
            editor.set(ENTRY_KEY_CACHE_DURATION, String.valueOf(cacheDuration));
            editor.set(ENTRY_KEY_CACHE_TIMESTAMP, String.valueOf(System.currentTimeMillis()));
            editor.commit();
        } catch (Exception e) {
            Timber.e("put:" + Log.getStackTraceString(e));
        }
    }

    public String get(String url) {
        try {
            String cacheKey = RxTool.Md5(url);
            DiskLruCache.Snapshot snapshot = cache.get(cacheKey);
            long cacheDuration = Long.parseLong(snapshot.getString(ENTRY_KEY_CACHE_DURATION));
            long cacheTimestamp = Long.parseLong(snapshot.getString(ENTRY_KEY_CACHE_TIMESTAMP));
            if (System.currentTimeMillis() - cacheTimestamp > cacheDuration) {
                cache.remove(cacheKey);
                return "";
            }
            return snapshot.getString(ENTRY_KEY_VALUE);
        } catch (Exception e) {
            Timber.e("get:" + Log.getStackTraceString(e));
            return "";
        }
    }


    public File getDiskCacheDir() {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
            cachePath = MyApp.getAppContext().getExternalCacheDir().getPath();
        } else {
            cachePath = MyApp.getAppContext().getCacheDir().getPath();
        }
        File file = new File(cachePath + File.separator + "http" + File.separator);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    public int getAppVersion() {
        try {
            PackageInfo info = MyApp.getAppContext().getPackageManager().getPackageInfo(MyApp.getAppContext().getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            Timber.e("getAppVersion:" + Log.getStackTraceString(e));
        }
        return 1;
    }

    public void close() {
        try {
            cache.close();
        } catch (Exception e) {
            Timber.e("close:" + Log.getStackTraceString(e));
        }
    }

    public void delete() {
        try {
            cache.delete();
        } catch (Exception e) {
            Timber.e("delete:" + Log.getStackTraceString(e));
        }
    }

    public long size() {
        return cache.size();
    }

    public void flush() {
        try {
            cache.flush();
        } catch (Exception e) {
            Timber.e("flush:"+Log.getStackTraceString(e));
        }
    }
}
